using System;
using System.Collections.Concurrent;

namespace IQIGame.Onigao.Framework
{
    public class ThreadHelper : Singleton<ThreadHelper>
    {
        private ConcurrentQueue<Action> m_ActionQueue = new ConcurrentQueue<Action>();

        private ThreadHelper()
        {
            if (FrameworkEntry.MonoDriver == null)
            {
                throw new FrameworkException("FrameworkEntry.MonoDriver is not prepaerd yet.");
            }
            FrameworkEntry.MonoDriver.updateEvent += OnUpdate;
        }

        private void OnUpdate(float deltaTime, float unscaledDeltaTime)
        {
            while (m_ActionQueue.TryDequeue(out Action action))
            {
                action();
            }
        }

        public void CallInMainThread(Action action)
        {
            m_ActionQueue.Enqueue(action);
        }
    }
}
